"""
RBAC 相关接口：资源、角色资源等
"""
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session

from utils.database import get_db
from Models.login.models import Resource, RoleResource, Role, User
from Models.login.schemas import Response
from utils import JWTUtils

router = APIRouter(prefix="/home", tags=["RBAC"])


def build_tree(resources):
    nodes = {r.id: {
        "id": r.id,
        "name": r.name,
        "code": r.code,
        "type": r.type,
        "path": r.path,
        "icon": r.icon,
        "sort": r.sort,
        "parent_id": r.parent_id,
        "children": []
    } for r in resources}
    roots = []
    for r in resources:
        node = nodes[r.id]
        if r.parent_id and r.parent_id in nodes:
            nodes[r.parent_id]["children"].append(node)
        else:
            roots.append(node)
    # 排序
    def sort_children(n):
        n["children"].sort(key=lambda x: x["sort"])
        for c in n["children"]:
            sort_children(c)
    for root in roots:
        sort_children(root)
    roots.sort(key=lambda x: x["sort"])
    return roots


@router.get("/resources", response_model=Response, summary="获取全部资源树（管理员）")
async def list_all_resources(db: Session = Depends(get_db)):
    resources = db.query(Resource).filter(Resource.is_active == True).all()
    return Response(code=200, message="success", data={"resources": build_tree(resources)})


@router.get("/my/resources", response_model=Response, summary="获取当前用户资源树")
async def my_resources(request: Request, db: Session = Depends(get_db)):
    authorization = request.headers.get("Authorization")
    if not authorization:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="未提供认证令牌")
    try:
        token = authorization.split(" ")[1]
    except Exception:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌格式错误")

    payload = JWTUtils.decode_access_token(token)
    if not payload or not payload.get("user_id"):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌无效或已过期")

    user = db.query(User).filter(User.id == payload["user_id"]).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    if not user.role_id:
        return Response(code=200, message="success", data={"resources": []})

    # 查角色资源
    rr = db.query(RoleResource).filter(RoleResource.role_id == user.role_id).all()
    res_ids = [x.resource_id for x in rr]
    if not res_ids:
        return Response(code=200, message="success", data={"resources": []})

    resources = db.query(Resource).filter(Resource.id.in_(res_ids), Resource.is_active == True).all()
    return Response(code=200, message="success", data={"resources": build_tree(resources)})


@router.post("/role/{role_id}/resources", response_model=Response, summary="为角色分配资源")
async def set_role_resources(role_id: int, body: dict, db: Session = Depends(get_db)):
    """body: {"resource_ids": [1,2,3]}"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")

    ids = body.get("resource_ids") or []
    # 先清空
    db.query(RoleResource).filter(RoleResource.role_id == role_id).delete()
    for rid in ids:
        db.add(RoleResource(role_id=role_id, resource_id=int(rid)))
    db.commit()
    return Response(code=200, message="已更新角色资源", data={"role_id": role_id, "count": len(ids)})


